/**
 * @description User Controller
 */

 const {
  createUser,
  getUserInfo,
  updateUser,
  deleteUser,
  queryAll
} = require('../service/user')
const { SuccessModel, ErrorModel } = require('../model/ResModel')
const {
  registerFailInfo,
  unCorrectPwd,
  loginFailInfo,
  loginCheckFailInfo,
  updateFailInfo,
  deleteUserFailInfo,
  queryFailInfo,
  operationFailInfo
} = require('../model/ErrorInfo')

/**
 * 用户注册或登录
 * @param {string} userid 用户ID
 * @param {string} nikename 昵称
 * @param {string} city 城市
 * @param {string} avatar 头像
 */
async function login({ username, password }) {
  const userInfo = await getUserInfo(username)
  if (userInfo) {
    // 查看密码是否一致
    if (password === userInfo.password) {
      return new SuccessModel(userInfo)
    } else {
      return new ErrorModel({
        code: 500,
        msg: '密码不正确'
      })
    }
  } else {
    return new ErrorModel({
      code: 500,
      msg: '账号不存在'
    })
  }
}

async function register({username, password, email}) {
  const userObj = {
    username,
    password,
    email
  }
  const userInfo = await getUserInfo(username)
  if (userInfo) {
    return new ErrorModel({
      code: 500,
      msg: '账号已存在'
    })
  }
  try {
    await createUser(userObj)
    return new SuccessModel(userObj)
  } catch (ex) {
    return new ErrorModel(registerFailInfo)
  }
}

/**
 * 查询所有用户（支持条件查询和模糊查询）
 * @param {string} nikename 用户昵称 
 * @param {string} userid 用户id 
 * @param {number} page 当前页码
 * @param {number} pageSize 每页条数 
 * @returns 
 */
async function queryAllUser({ nikename, userid, page, pageSize }) {
  try {
    const result = await queryAll({ nikename, userid, page, pageSize })
    return new SuccessModel(result)
  } catch (ex) {
    return new ErrorModel(queryFailInfo)
  }
}

/**
 * 修改用户信息
 * @param {object} updateInfo 要修改的信息
 * @param {objcet} whereInfo 查询条件
 */
async function updateUserInfo(updateInfo, whereInfo) {
  try {
    const result = await updateUser(updateInfo, whereInfo)
    return new SuccessModel({ result })
  } catch (ex) {
    return new ErrorModel(updateFailInfo)
  }
}

/**
 * 冻结账户
 * @param {string} userid 用户id 
 */
async function freezeAccount({ userid }) {
  try {
    const result = await updateUser(
      { isVip: -1 },
      { userid }
    )
    return new SuccessModel({ result })
  } catch (ex) {
    return new ErrorModel(operationFailInfo)
  }
}

module.exports = {
  login,
  register,
  queryAllUser,
  updateUserInfo,
  freezeAccount
}
